package com.jshcbd.mvp_kt_demo.http

import com.jshcbd.mvp_kt_demo.app.MyApplication
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

class ApiEngine private constructor() {
    private val retrofit: Retrofit
    fun getRetrofit(): Retrofit {
        return retrofit
    }

    companion object {
        @Volatile
        private var apiEngine: ApiEngine? = null
        val instance: ApiEngine?
            get() {
                if (apiEngine == null) {
                    synchronized(ApiEngine::class.java) {
                        if (apiEngine == null) {
                            apiEngine = ApiEngine()
                        }
                    }
                }
                return apiEngine
            }
    }

    init {
        //日志拦截器
        val loggingInterceptor = HttpLoggingInterceptor(HttpLogger())
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        //缓存
        val size = 1024 * 1024 * 100
        val cacheFile: File = File(MyApplication.application?.cacheDir, "OkHttpCache")
        val cache = Cache(cacheFile, size.toLong())
        val client: OkHttpClient = OkHttpClient.Builder()
            .connectTimeout(12, TimeUnit.SECONDS)
            .readTimeout(12, TimeUnit.SECONDS)
            .writeTimeout(12, TimeUnit.SECONDS)
            .addNetworkInterceptor(NetworkInterceptor()) //网络缓存设置
            .addInterceptor(loggingInterceptor)
            .cache(cache)
            .build()
        retrofit = Retrofit.Builder()
            .baseUrl(ApiHost.IP_UAT!!)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }
}